﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;

using MichaelKappel.Net.HelloWorld.NetNamedPipeBinding;
using MichaelKappel.Net.HelloWorld.NetNamedPipeBinding.Interfaces;

namespace NetNamedPipeBindingClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }
        private Boolean active = false;
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            active = true;
            SendUpdate();
            btnStart.IsEnabled = false;
            btnStop.IsEnabled = true;
        }
        private void btnStop_Click(object sender, RoutedEventArgs e)
        {

            btnStart.IsEnabled = true;
            btnStop.IsEnabled = false;
            active = false;
        }
        private void SendUpdate()
        {
            this.Background = Brushes.Gray;
            txtMessage.Text = "Working...";

            string address = "net.pipe://localhost/HelloWorld/NetNamedPipeBindingHost";

            NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
            EndpointAddress ep = new EndpointAddress(address);

            ITestService channel =
                ChannelFactory<ITestService>.CreateChannel(
                    binding, ep
                );

            using (channel as IDisposable)
            {
                try
                {
                    Boolean result = channel.Test(txtName.Text);
                    this.Background = Brushes.LightBlue;
                    txtMessage.Text = "OK :) " + DateTime.Now.TimeOfDay;
                }
                catch (Exception ex)
                {
                    this.Background = Brushes.Coral;
                    txtMessage.Text = ex.Message;
                }
            }
        }

        private void txtName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (active)
                SendUpdate();
        }

    }
}
